<template>
  <div>
    <el-form label-width="100px" class="form-container">
      <h2>基本信息</h2>
      <el-divider></el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="头像：">
            <el-upload
                v-model:file-list="avatarFileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleAvatarSuccess"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别：" required>
            <el-radio-group v-model="blueResumeData.gender">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名：" required>
            <el-input placeholder="请输入" v-model="blueResumeData.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生日：" required>
            <el-input placeholder="我们绝为你保密" v-model="blueResumeData.birthday"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号：" required>
            <el-input placeholder="方便收到面试邀请电话" v-model="blueResumeData.userContact"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱：" required>
            <el-input placeholder="用于接收面试邮件" v-model="blueResumeData.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="微信号：" required>
            <el-input placeholder="用于与HR交换微信" v-model="blueResumeData.wechat"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="居住城市：" required>
            <el-input placeholder="你现在住哪里" v-model="blueResumeData.city"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="期望工作：" required>
            <el-input placeholder="想找什么工作" v-model="blueResumeData.jobExpectation"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="期望薪水：" required>
            <el-input placeholder="期望薪水是多少" v-model="blueResumeData.salaryExpectation"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作时间：" required>
            <el-date-picker
                v-model="blueResumeData.workTime"
                type="date"
                placeholder="请选择参加工作时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职业状态：" required>
            <el-select placeholder="请选择职业状态" v-model="blueResumeData.careerStatus">
              <el-option label="在职" value="employed"></el-option>
              <el-option label="离职" value="unemployed"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="自我介绍：" required>
        <el-input type="textarea" placeholder="请输⼊内容" rows="4" v-model="blueResumeData.introduction"></el-input>
      </el-form-item>
      <!-- 添加技工证书上传 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <h2 style="margin-top: 20px; margin-bottom: 0;">技工证书</h2>
        </el-col>
        <el-col :span="12" style="text-align: right; margin-top: 15px">
          <el-upload
              :action="actionUrl"
              :on-success="handleCertSuccess"
              :on-remove="handleRemove"
              v-model:file-list="certFileList"
              accept=".pdf,.doc,.docx,.jpg"
              :before-upload="beforeUpload"
          >
            <el-button type="primary" icon="el-icon-plus" style="text-align: center">添加技工证书</el-button>
          </el-upload>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-form-item>
        <div style="margin-top: 10px; font-size: 12px; color: #999;">
          支持上传格式：PDF/WORD/JPG，大小：500MB以下
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="cancel" type="default">取消</el-button>
        <el-button @click="submitForm" type="primary">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import {computed, onBeforeUnmount, onMounted, ref} from 'vue';
import {ElMessage} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import axios from "axios";
import qs from "qs";
import {useStore} from "vuex";
import router from "@/router";

const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const certFileList = ref([]);  // 专门存储证书文件
const actionUrl=ref('http://localhost:9093/v1/file/upload')
const avatarFileList = ref([]); // 存储头像上传的文件列表
const baseUrl ='http://localhost:9093/';
const store=useStore();
// const resumeData=computed(()=>store.state.resumeData);
const currentResume=computed(()=>store.state.currentResume);
// 打印数据（调试用）
const logData = () => {
  console.log('当前简历 回显 数据:', store.state.currentResume);
};
const initFileLists = () => {
  const resume = currentResume.value;

  // 初始化头像 fileList
  if (resume && resume.photoImgUrl) {
    avatarFileList.value = [{
      name: 'avatar.jpg',
      url: baseUrl + resume.photoImgUrl,
      response: { data: resume.photoImgUrl } // 模拟上传响应结构
    }];
  }

  // 初始化证书 fileList
  if (resume && resume.certificateUrl) {
    certFileList.value = [{
      name: 'certificate.pdf',
      url: baseUrl + resume.certificateUrl,
      response: { data: resume.certificateUrl } // 模拟上传响应结构
    }];
  }
};

onMounted(() => {
  logData();

  if (currentResume.value && Object.keys(currentResume.value).length > 0) {
    // 回显表单数据
    Object.assign(blueResumeData.value, currentResume.value);

    // 初始化文件列表
    initFileLists();
  } else {
    resetForm();
  }
});

//定义保存表单的数据
const blueResumeData = ref({
  id:null,
  gender: '',
  name: '',
  birthday: '',
  userContact: '',
  email: '',
  wechat: '',
  city: '',
  jobExpectation: '',
  salaryExpectation: '',
  workTime: '',
  careerStatus: '',
  introduction: '',
  photoImgUrl: '',
  certificateUrl: ''
});

const submitForm = async () => {
  try {
    // 1. 校验必须文件
    if (!avatarFileList.value.length) {
      ElMessage.error('请上传头像');
      return;
    }
    if (!certFileList.value.length) {
      ElMessage.error('请上传证书文件');
      return;
    }

    // 2. 安全获取文件地址
    blueResumeData.value.photoImgUrl = avatarFileList.value[0]?.response?.data;
    blueResumeData.value.certificateUrl = certFileList.value[0]?.response?.data;

    // 3. 验证文件地址是否存在
    if (!blueResumeData.value.photoImgUrl || !blueResumeData.value.certificateUrl) {
      ElMessage.error('文件上传未完成，请稍后重试');
      return;
    }

    // 4. 发送请求
    let data=qs.stringify(blueResumeData.value);
    axios.post('http://localhost:9093/v1/resume/save',data)
        .then(response => {
          if (response.data.state === 200) {
            ElMessage.success(response.data.message);
          } else {
            ElMessage.error(response.data.message);
          }

        })

    // 5. 处理响应
    await router.push('/resumeList')

  } catch (error) {
    ElMessage.error(`提交失败: ${error.message}`);
  }
};
const cancel = () => {
  // 处理取消逻辑
  blueResumeData.value = {};
};
const handleRemove = (file) => {
  if (!file.response?.data) return;

  axios.post('http://localhost:9093/v1/file/remove', {
    imgUrl: file.response.data
  }).then(response => {
    if (response.data.code === 2000) {
      ElMessage.success('删除成功');
      // 自动更新文件列表，无需手动清除
    }
  });
};
const handleAvatarSuccess = (response) => {
  blueResumeData.value.photoImgUrl = response.data;
  ElMessage.success('头像上传成功');
};
// 证书上传成功
const handleCertSuccess = (response) => {
  blueResumeData.value.certificateUrl = response.data;
  ElMessage.success('证书上传成功');
};
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
  console.log(uploadFile.url);
};

const handleUploadSuccess = (response, file, fileList) => {
  // 处理上传成功后的逻辑
  console.log('Upload success:', response, file, fileList);
  ElMessage.success('上传成功');
  blueResumeData.value.certificates = fileList?.map(file => file.name) || [];
};

const beforeUpload = (file) => {
  const isLt500M = file.size / 1024 / 1024 < 500;
  if (!isLt500M) {
    ElMessage.error('文件大小不能超过 500MB!');
  }
  return isLt500M;
};
// //页面销毁时清空回显数据
// const resetForm = () => {
//   Object.keys(blueResumeData.value).forEach(key => {
//     blueResumeData.value[key] = '';
//   });
//   avatarFileList.value = [];
//   certFileList.value = [];
// };
//
// onBeforeUnmount(() => {
//   resetForm();
//   console.log('组件销毁前，数据已重置');
// });

</script>


<style scoped>
.form-container {

  max-width: 800px;
  margin: 0 auto;
  background-color: white;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  border-radius: 8px; /* 可选：圆角边框 */
}
</style>